<template>
  <div class="admin-forum-view">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">论坛管理</h1>
      <p class="page-subtitle">管理论坛的帖子、评论和版块</p>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="search-filters">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索帖子标题或内容"
          prefix-icon="Search"
          class="search-input"
          @keyup.enter="searchPosts"
        />
        <el-select v-model="postStatus" placeholder="帖子状态" class="status-select">
          <el-option label="全部" value="" />
          <el-option label="正常" value="normal" />
          <el-option label="精华" value="featured" />
          <el-option label="置顶" value="sticky" />
          <el-option label="已删除" value="deleted" />
        </el-select>
        <el-select v-model="postCategory" placeholder="帖子分类" class="category-select">
          <el-option label="全部" value="" />
          <el-option label="学习交流" value="study" />
          <el-option label="经验分享" value="experience" />
          <el-option label="问题求助" value="help" />
          <el-option label="资料共享" value="resource" />
          <el-option label="考试资讯" value="news" />
        </el-select>
      </div>
      <div class="toolbar-actions">
        <el-button type="primary" @click="manageCategories">管理版块</el-button>
        <el-button type="default" @click="exportPostList">导出帖子列表</el-button>
      </div>
    </div>

    <!-- 数据统计 -->
    <div class="stats-cards">
      <el-card class="stat-card">
        <div class="stat-content">
          <span class="stat-number">{{ totalPosts }}</span>
          <span class="stat-label">总帖子数</span>
        </div>
        <el-icon class="stat-icon"><Document /></el-icon>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <span class="stat-number">{{ todayPosts }}</span>
          <span class="stat-label">今日新增</span>
        </div>
        <el-icon class="stat-icon"><Add /></el-icon>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <span class="stat-number">{{ pendingPosts }}</span>
          <span class="stat-label">待审核</span>
        </div>
        <el-icon class="stat-icon"><Hourglass /></el-icon>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <span class="stat-number">{{ deletedPosts }}</span>
          <span class="stat-label">已删除</span>
        </div>
        <el-icon class="stat-icon"><Delete /></el-icon>
      </el-card>
    </div>

    <!-- 帖子表格 -->
    <el-card class="table-card">
      <el-table
        v-loading="isLoading"
        :data="postsData"
        style="width: 100%"
        border
        highlight-current-row
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="postId" label="帖子ID" width="100" />
        <el-table-column prop="title" label="标题" min-width="300">
          <template #default="scope">
            <div class="post-title">
              <span v-for="tag in getPostTags(scope.row)" :key="tag.type" class="post-tag" :class="`tag-${tag.type}`">
                {{ tag.text }}
              </span>
              <span class="title-text">{{ scope.row.title }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="120">
          <template #default="scope">
            <el-tag>{{ getCategoryLabel(scope.row.category) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="author" label="作者" min-width="120">
          <template #default="scope">
            <div class="author-info">
              <el-avatar size="24" class="author-avatar">
                <span>{{ scope.row.author.nickname.charAt(0).toUpperCase() }}</span>
              </el-avatar>
              <span class="author-name">{{ scope.row.author.nickname }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="views" label="浏览量" width="80" />
        <el-table-column prop="replies" label="回复数" width="80" />
        <el-table-column prop="likes" label="点赞数" width="80" />
        <el-table-column prop="createTime" label="发布时间" min-width="150" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewPostDetail(scope.row)">查看</el-button>
            <el-button 
              type="default" 
              size="small" 
              :class="scope.row.status === 'normal' ? 'text-warning' : 'text-success'"
              @click="toggleFeatured(scope.row)"
            >
              {{ scope.row.status === 'featured' ? '取消精华' : '设为精华' }}
            </el-button>
            <el-button 
              type="default" 
              size="small" 
              :class="scope.row.status === 'normal' || scope.row.status === 'featured' ? 'text-warning' : 'text-success'"
              @click="toggleSticky(scope.row)"
            >
              {{ scope.row.status === 'sticky' ? '取消置顶' : '置顶' }}
            </el-button>
            <el-button 
              type="default" 
              size="small" 
              class="text-danger"
              @click="deletePost(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 帖子详情模态框 -->
    <el-dialog v-model="showPostDetailModal" :title="`帖子详情 - ${selectedPost?.title}`" width="800px" append-to-body>
      <div v-if="selectedPost" class="post-detail">
        <div class="detail-header">
          <h3 class="detail-title">
            <span v-for="tag in getPostTags(selectedPost)" :key="tag.type" class="post-tag" :class="`tag-${tag.type}`">
              {{ tag.text }}
            </span>
            {{ selectedPost.title }}
          </h3>
          <div class="detail-meta">
            <div class="author-info">
              <el-avatar size="32" class="author-avatar">
                <span>{{ selectedPost.author.nickname.charAt(0).toUpperCase() }}</span>
              </el-avatar>
              <span class="author-name">{{ selectedPost.author.nickname }}</span>
              <span class="author-role">{{ getRoleLabel(selectedPost.author.role) }}</span>
            </div>
            <div class="post-stats">
              <span class="stat-item">浏览: {{ selectedPost.views }}</span>
              <span class="stat-item">回复: {{ selectedPost.replies }}</span>
              <span class="stat-item">点赞: {{ selectedPost.likes }}</span>
              <span class="stat-item">发布于: {{ selectedPost.createTime }}</span>
            </div>
          </div>
        </div>

        <div class="post-content" v-html="selectedPost.content"></div>

        <div class="detail-actions">
          <el-button 
            type="primary" 
            size="small" 
            @click="toggleFeatured(selectedPost)"
          >
            {{ selectedPost.status === 'featured' ? '取消精华' : '设为精华' }}
          </el-button>
          <el-button 
            type="primary" 
            size="small" 
            @click="toggleSticky(selectedPost)"
          >
            {{ selectedPost.status === 'sticky' ? '取消置顶' : '置顶' }}
          </el-button>
          <el-button 
            type="danger" 
            size="small" 
            @click="deletePost(selectedPost)"
          >
            删除帖子
          </el-button>
        </div>

        <!-- 评论列表 -->
        <div class="comments-section" v-if="selectedPost.comments && selectedPost.comments.length > 0">
          <h4 class="section-title">评论列表 ({{ selectedPost.comments.length }})</h4>
          <div class="comments-list">
            <div v-for="comment in selectedPost.comments" :key="comment.commentId" class="comment-item">
              <div class="comment-header">
                <el-avatar size="24" class="comment-avatar">
                  <span>{{ comment.author.nickname.charAt(0).toUpperCase() }}</span>
                </el-avatar>
                <span class="comment-author">{{ comment.author.nickname }}</span>
                <span class="comment-time">{{ comment.createTime }}</span>
              </div>
              <div class="comment-content" v-html="comment.content"></div>
              <div class="comment-actions">
                <el-button type="text" size="small" class="text-danger" @click="deleteComment(comment)">删除</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="showPostDetailModal = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 版块管理模态框 -->
    <el-dialog v-model="showCategoriesModal" title="版块管理" width="600px">
      <div class="categories-management">
        <div class="categories-list">
          <div v-for="category in categories" :key="category.id" class="category-item">
            <div class="category-info">
              <span class="category-name">{{ category.name }}</span>
              <span class="category-count">({{ category.postCount }}篇帖子)</span>
            </div>
            <div class="category-actions">
              <el-button type="text" size="small" @click="editCategory(category)">编辑</el-button>
              <el-button type="text" size="small" class="text-danger" @click="deleteCategory(category)">删除</el-button>
            </div>
          </div>
        </div>
        <div class="add-category">
          <el-input v-model="newCategoryName" placeholder="输入新版块名称" class="category-input" />
          <el-button type="primary" size="small" @click="addCategory">添加版块</el-button>
        </div>
      </div>
      <template #footer>
        <el-button @click="showCategoriesModal = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 搜索和筛选条件
const searchKeyword = ref('');
const postStatus = ref('');
const postCategory = ref('');

// 加载状态
const isLoading = ref(false);

// 模态框控制
const showPostDetailModal = ref(false);
const showCategoriesModal = ref(false);

// 选择的帖子
const selectedPost = ref<any>(null);

// 统计数据
const totalPosts = ref(2568);
const todayPosts = ref(35);
const pendingPosts = ref(8);
const deletedPosts = ref(120);

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 2568
});

// 版块数据
const categories = ref([
  { id: 'study', name: '学习交流', postCount: 856 },
  { id: 'experience', name: '经验分享', postCount: 623 },
  { id: 'help', name: '问题求助', postCount: 412 },
  { id: 'resource', name: '资料共享', postCount: 389 },
  { id: 'news', name: '考试资讯', postCount: 288 }
]);

// 新版块名称
const newCategoryName = ref('');

// 模拟帖子数据
const postsData = ref<any[]>([
  {
    postId: 'P001',
    title: '行测判断推理技巧分享，这些方法让你轻松拿高分',
    content: '<p>大家好，今天给大家分享一下行测判断推理部分的解题技巧...</p>',
    category: 'study',
    author: {
      nickname: '行测大神',
      role: 'moderator'
    },
    views: 2356,
    replies: 45,
    likes: 189,
    status: 'featured',
    createTime: '2024-05-10 14:30:00',
    comments: [
      {
        commentId: 'C001',
        author: {
          nickname: '公考小白'
        },
        content: '<p>感谢分享，这些技巧很实用！</p>',
        createTime: '2024-05-10 15:20:00'
      }
    ]
  },
  {
    postId: 'P002',
    title: '2024年国考申论真题解析及参考答案',
    content: '<p>2024年国考已经结束，现在为大家带来申论部分的真题解析...</p>',
    category: 'experience',
    author: {
      nickname: '申论小王子',
      role: 'user'
    },
    views: 3421,
    replies: 89,
    likes: 256,
    status: 'sticky',
    createTime: '2024-05-09 10:15:00',
    comments: []
  },
  {
    postId: 'P003',
    title: '请问资料分析有什么快速解题的方法吗？',
    content: '<p>最近在复习资料分析，发现时间总是不够用...</p>',
    category: 'help',
    author: {
      nickname: '新手上路',
      role: 'user'
    },
    views: 1256,
    replies: 23,
    likes: 45,
    status: 'normal',
    createTime: '2024-05-08 16:45:00',
    comments: []
  },
  {
    postId: 'P004',
    title: '【资料共享】2024年最新时政热点汇总',
    content: '<p>整理了2024年1-5月的时政热点，分享给大家...</p>',
    category: 'resource',
    author: {
      nickname: '时政小达人',
      role: 'user'
    },
    views: 5678,
    replies: 124,
    likes: 345,
    status: 'normal',
    createTime: '2024-05-07 09:30:00',
    comments: []
  },
  {
    postId: 'P005',
    title: '2024年省考报名时间及考试安排',
    content: '<p>根据最新消息，2024年省考报名时间确定...</p>',
    category: 'news',
    author: {
      nickname: '公考资讯站',
      role: 'user'
    },
    views: 4321,
    replies: 98,
    likes: 234,
    status: 'normal',
    createTime: '2024-05-06 11:20:00',
    comments: []
  }
]);

// 获取帖子标签
const getPostTags = (post: any) => {
  const tags: any[] = [];
  if (post.status === 'featured') {
    tags.push({ type: 'featured', text: '精华' });
  }
  if (post.status === 'sticky') {
    tags.push({ type: 'sticky', text: '置顶' });
  }
  if (post.status === 'deleted') {
    tags.push({ type: 'deleted', text: '已删除' });
  }
  return tags;
};

// 获取分类标签文本
const getCategoryLabel = (category: string) => {
  const categoryMap: Record<string, string> = {
    study: '学习交流',
    experience: '经验分享',
    help: '问题求助',
    resource: '资料共享',
    news: '考试资讯'
  };
  return categoryMap[category] || category;
};

// 获取角色标签文本
const getRoleLabel = (role: string) => {
  const roleMap: Record<string, string> = {
    admin: '管理员',
    moderator: '版主',
    user: '普通用户'
  };
  return roleMap[role] || role;
};

// 搜索帖子
const searchPosts = () => {
  // 模拟搜索逻辑
  isLoading.value = true;
  setTimeout(() => {
    isLoading.value = false;
    ElMessage.success('搜索完成');
  }, 500);
};

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  loadPosts();
};

const handleCurrentChange = (current: number) => {
  pagination.currentPage = current;
  loadPosts();
};

// 加载帖子数据
const loadPosts = () => {
  // 模拟加载数据
  isLoading.value = true;
  setTimeout(() => {
    isLoading.value = false;
    // 这里应该是实际的加载数据逻辑
  }, 500);
};

// 查看帖子详情
const viewPostDetail = (post: any) => {
  selectedPost.value = { ...post };
  showPostDetailModal.value = true;
};

// 切换精华状态
const toggleFeatured = (post: any) => {
  const newStatus = post.status === 'featured' ? 'normal' : 'featured';
  
  // 模拟更新帖子状态
  isLoading.value = true;
  setTimeout(() => {
    isLoading.value = false;
    // 更新本地数据
    const index = postsData.value.findIndex(p => p.postId === post.postId);
    if (index !== -1) {
      postsData.value[index].status = newStatus;
    }
    if (selectedPost.value && selectedPost.value.postId === post.postId) {
      selectedPost.value.status = newStatus;
    }
    ElMessage.success(`帖子${newStatus === 'featured' ? '设为精华' : '取消精华'}成功`);
  }, 500);
};

// 切换置顶状态
const toggleSticky = (post: any) => {
  const newStatus = post.status === 'sticky' ? 'normal' : 'sticky';
  
  // 模拟更新帖子状态
  isLoading.value = true;
  setTimeout(() => {
    isLoading.value = false;
    // 更新本地数据
    const index = postsData.value.findIndex(p => p.postId === post.postId);
    if (index !== -1) {
      postsData.value[index].status = newStatus;
    }
    if (selectedPost.value && selectedPost.value.postId === post.postId) {
      selectedPost.value.status = newStatus;
    }
    ElMessage.success(`帖子${newStatus === 'sticky' ? '置顶' : '取消置顶'}成功`);
  }, 500);
};

// 删除帖子
const deletePost = (post: any) => {
  ElMessageBox.confirm(
    '确定要删除此帖子吗？此操作不可撤销！',
    '警告',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'error'
    }
  ).then(() => {
    // 模拟删除帖子
    isLoading.value = true;
    setTimeout(() => {
      isLoading.value = false;
      // 更新本地数据
      postsData.value = postsData.value.filter(p => p.postId !== post.postId);
      if (selectedPost.value && selectedPost.value.postId === post.postId) {
        showPostDetailModal.value = false;
      }
      ElMessage.success('帖子删除成功');
    }, 500);
  }).catch(() => {
    ElMessage.info('已取消操作');
  });
};

// 删除评论
const deleteComment = (comment: any) => {
  ElMessageBox.confirm(
    '确定要删除此评论吗？',
    '警告',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'error'
    }
  ).then(() => {
    // 模拟删除评论
    if (selectedPost.value && selectedPost.value.comments) {
      selectedPost.value.comments = selectedPost.value.comments.filter((c: any) => c.commentId !== comment.commentId);
      ElMessage.success('评论删除成功');
    }
  }).catch(() => {
    ElMessage.info('已取消操作');
  });
};

// 管理版块
const manageCategories = () => {
  showCategoriesModal.value = true;
};

// 添加版块
const addCategory = () => {
  if (!newCategoryName.value.trim()) {
    ElMessage.warning('请输入版块名称');
    return;
  }
  
  // 模拟添加版块
  const newCategory = {
    id: `category_${Date.now()}`,
    name: newCategoryName.value.trim(),
    postCount: 0
  };
  categories.value.push(newCategory);
  newCategoryName.value = '';
  ElMessage.success('版块添加成功');
};

// 编辑版块
const editCategory = (_category: any) => {
  // 这里应该是实际的编辑版块逻辑
  ElMessage.info('编辑版块功能待实现');
};

// 删除版块
const deleteCategory = (category: any) => {
  ElMessageBox.confirm(
    `确定要删除版块"${category.name}"吗？`,
    '警告',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'error'
    }
  ).then(() => {
    // 模拟删除版块
    categories.value = categories.value.filter(c => c.id !== category.id);
    ElMessage.success('版块删除成功');
  }).catch(() => {
    ElMessage.info('已取消操作');
  });
};

// 导出帖子列表
const exportPostList = () => {
  // 模拟导出帖子列表
  ElMessage.success('帖子列表导出成功');
};
</script>

<style lang="scss" scoped>
.admin-forum-view {
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 30px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.page-subtitle {
  font-size: 14px;
  color: #6b7280;
  margin: 5px 0 0 0;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f9fafb;
  border-radius: 8px;
}

.search-filters {
  display: flex;
  gap: 15px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.status-select,
.category-select {
  width: 150px;
}

.toolbar-actions {
  display: flex;
  gap: 10px;
}

.stats-cards {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  transition: all 0.3s;

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
  }
}

.stat-content {
  display: flex;
  flex-direction: column;
}

.stat-number {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  line-height: 1.2;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
  margin-top: 5px;
}

.stat-icon {
  font-size: 36px;
  color: #6366f1;
  opacity: 0.8;
}

.table-card {
  border-radius: 8px;
  overflow: hidden;
}

.post-title {
  display: flex;
  align-items: center;
  gap: 5px;
  flex-wrap: wrap;
}

.post-tag {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 3px;
  color: white;
}

.tag-featured {
  background-color: #ec4899;
}

.tag-sticky {
  background-color: #f43f5e;
}

.tag-deleted {
  background-color: #6b7280;
}

.title-text {
  font-size: 14px;
  color: #1f2937;
  word-break: break-word;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.author-avatar {
  border: 2px solid #f3f4f6;
}

.author-name {
  font-size: 14px;
  color: #1f2937;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.post-detail {
  padding: 20px 0;
}

.detail-header {
  padding: 20px 0;
  border-bottom: 1px solid #e5e7eb;
  margin-bottom: 20px;
}

.detail-title {
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 15px 0;
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.detail-meta {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.post-stats {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #6b7280;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.post-content {
  padding: 20px 0;
  line-height: 1.8;
  color: #4b5563;
  font-size: 14px;
  border-bottom: 1px solid #e5e7eb;
}

.detail-actions {
  display: flex;
  gap: 10px;
  margin: 20px 0;
}

.comments-section {
  margin-top: 20px;
}

.comments-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.comment-item {
  padding: 15px;
  background-color: #f9fafb;
  border-radius: 8px;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.comment-avatar {
  border: 2px solid #f3f4f6;
}

.comment-author {
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
}

.comment-time {
  font-size: 12px;
  color: #9ca3af;
}

.comment-content {
  font-size: 14px;
  color: #4b5563;
  line-height: 1.6;
  margin-bottom: 10px;
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
}

.categories-management {
  padding: 20px 0;
}

.categories-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 20px;
}

.category-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background-color: #f9fafb;
  border-radius: 8px;
}

.category-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.category-name {
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
}

.category-count {
  font-size: 12px;
  color: #6b7280;
}

.add-category {
  display: flex;
  gap: 10px;
  align-items: center;
}

.category-input {
  flex: 1;
}

// 响应式设计
@media (max-width: 1200px) {
  .toolbar {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .search-filters {
    justify-content: space-between;
  }
  
  .stats-cards {
    flex-wrap: wrap;
  }
  
  .stat-card {
    flex: 1 1 calc(50% - 10px);
  }
}

@media (max-width: 768px) {
  .search-filters {
    flex-direction: column;
    gap: 10px;
  }
  
  .search-input,
  .status-select,
  .category-select {
    width: 100%;
  }
  
  .stat-card {
    flex: 1 1 100%;
  }
  
  .add-category {
    flex-direction: column;
    gap: 10px;
  }
  
  .category-input {
    width: 100%;
  }
}
</style>